package com.hl.toolkit.pay.controller;

import com.me.hao0.wepay.demo.support.WepayService;
import com.tencent.WXPay;
import com.tencent.protocol.pay_protocol.ScanPayReqData;
import com.tencent.protocol.pay_query_protocol.ScanPayQueryReqData;
import com.tencent.protocol.refund_protocol.RefundReqData;
import com.tencent.util.GetWxOrderno;
import com.tenpay.util.CommonUtil;
import com.tenpay.util.Constants;
import com.tycoin.account.slaveentity.TycoinAccountRecharge;
import com.tycoin.account.slaveservice.TycoinAccountRechargeCallbackProcessService;
import com.tycoin.account.slaveservice.TycoinAccountRechargeService;
import com.tycoin.common.entity.AliWxPayInfo;
import com.util.DateUtils;
import com.util.IpRequestUtils;
import com.util.RandomUtils;
import com.util.XMLUtils;
import net.sf.json.JSONObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.BufferedReader;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

/**
 * 支付 Author: haolin Email: haolin.h0@gmail.com Date: 2/12/15
 */
@Controller
@RequestMapping("/interface/wepayScann")
public class WepayPayScannController {

	private static final Logger log = LoggerFactory.getLogger(WepayPayScannController.class);
	
	@Autowired
	private TycoinAccountRechargeService tycoinAccountRechargeService;
	@Autowired
	private TycoinAccountRechargeCallbackProcessService tycoinAccountRechargeCallbackProcessService;
	
	private int number=1;

	@RequestMapping(value ="/WepaySc",produces="application/json;charset=UTF-8",method=RequestMethod.GET)
	@ResponseBody
	public String weScannPay(HttpServletRequest request, HttpServletResponse response) {
 		String result_code = "";
		String return_code="";
		String return_msg = "";
		String cash_fee = "";
		String transaction_id = "";
		String err_code_des = "";
		String err_code = "";

		
		System.out.println("---------------------------------------------进来了："+(number++)+"次");

        Map<String,String> putMap=new HashMap<String,String>();
        
     putMap.put("AuthCode", request.getParameter("AuthCode"));
     putMap.put("Charge", request.getParameter("Charge"));
     putMap.put("GoodsName", request.getParameter("GoodsName"));
   //  putMap.put("CreatTime", request.getParameter("CreatTime"));
      putMap.put("PayType", request.getParameter("PayType"));
     putMap.put("UserId", request.getParameter("UserId"));
     putMap.put("AddIp", IpRequestUtils.getRemoteHost(request));
    String resultStr=isNotparam(putMap);
	     if(org.apache.commons.lang3.StringUtils.isNotBlank(resultStr)){
	    	 return resultStr;
	     }

      AliWxPayInfo payInfo=new AliWxPayInfo();
	payInfo.setAuthCode(putMap.get("AuthCode"));
	payInfo.setCharge(Double.valueOf(putMap.get("Charge")));
	payInfo.setGoodsName(putMap.get("GoodsName"));
  	payInfo.setPayType(Integer.valueOf(putMap.get("PayType")));
	payInfo.setUserId(Integer.valueOf(putMap.get("UserId")));
	payInfo.setAddIp(putMap.get("AddIp"));
		
		TycoinAccountRecharge tycoinAccountRecharge=new TycoinAccountRecharge();

     String result="";
		if (null != payInfo) {
			if (payInfo.getCharge() > 0) {
				long current= System.currentTimeMillis();
				
 				String outTradeNo = "WxTran" +current+ (long) (Math.random() * 1000000000000L);
  			    SimpleDateFormat formatter3 = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");  
  			    String order_create_time3=formatter3.format(current); 
 			    
  			  tycoinAccountRecharge.setLogno(RandomUtils.getRandomString(16));
 				tycoinAccountRecharge.setPaymentId(outTradeNo);
 				tycoinAccountRecharge.setDateTime(current);
  				tycoinAccountRecharge.setFee("0");
 				tycoinAccountRecharge.setIsOnline("0");
 				tycoinAccountRecharge.setMoney(String.valueOf((int)payInfo.getCharge()));
 				tycoinAccountRecharge.setMoneyfloat(((float)payInfo.getCharge())/100);
  				tycoinAccountRecharge.setType(String.valueOf(payInfo.getPayType()));
 				tycoinAccountRecharge.setUserId(String.valueOf(payInfo.getUserId()));
 				tycoinAccountRecharge.setAddip(payInfo.getAddIp());
 				tycoinAccountRecharge.setPaymentStatus(0);
 				tycoinAccountRecharge.setPaymentTime(order_create_time3);

 				tycoinAccountRecharge.setPayMode(1);
 			     tycoinAccountRechargeService.save(tycoinAccountRecharge);
 			    String result2="";
 				ScanPayReqData scanPayReqData = new ScanPayReqData(payInfo.getAuthCode(),
						"pay" + payInfo.getCharge(), DateUtils.formatDateTime2(new Date()), outTradeNo,
						1, "000", payInfo.getAddIp(),  DateUtils.formatDateTime2(new Date()),DateUtils.addMinute(5, new Date()), "wzhj","");
				try {
					  result2 = WXPay.requestScanPayService(scanPayReqData);
				} catch (Exception e) {
					System.out.println(e.getMessage());
				}
				Map<String, String> resultMap = new HashMap<String, String>();
				try {
					resultMap = XMLUtils.getResult(result2);
				} catch (Exception e) {
				}
 				tycoinAccountRecharge.setReturnText(result2);
 
				result_code =resultMap.get("result_code");
				return_code = resultMap.get("return_code");
		         System.out.println("------------return_code=");
		         System.out.println("------------return_code="+return_code+",result_code="+result_code);
				return_msg = resultMap.get("return_msg");
				err_code =  resultMap.get("err_code");
				err_code_des =resultMap.get("err_code_des");

				if ("SUCCESS".equals(result_code)) {
					cash_fee = resultMap.get("cash_fee");
					transaction_id = resultMap.get("transaction_id");
					System.out.println("************************************transaction_id"+transaction_id);
					tycoinAccountRecharge.setPaymentStatus(1);
					tycoinAccountRecharge.setShopTradeNo(transaction_id);
 					tycoinAccountRechargeService.save(tycoinAccountRecharge);
   		   			tycoinAccountRechargeCallbackProcessService.rechargeCallbackProcess(tycoinAccountRecharge); 
					result = "{\"result_code\":\"0000\",\"return_msg\":\"ok\",\"transaction_id\":\"" +outTradeNo + "\"}";

				} else {
					err_code = (String) resultMap.get("err_code");
					err_code_des = (String) resultMap.get("err_code_des");
					if("FAIL".equals(result_code)){
						result = "{\"result_code\":\"" + err_code + "\",\"return_msg\":\"" + err_code_des+ "\",\"transaction_id\":\"" +outTradeNo + "\"}";
		 				tycoinAccountRecharge.setPaymentStatus(2);
  					}
			 	  else{
							result = "{\"result_code\":\"" + err_code + "\",\"return_msg\":\"" + err_code_des+ "\",\"transaction_id\":\"" +outTradeNo + "\"}";
							tycoinAccountRecharge.setPaymentStatus(2);

			        }
					tycoinAccountRechargeService.save(tycoinAccountRecharge);
					return result;

 				}
 			}
		}
 		return result;
	}

	@RequestMapping(value = "/findScannPayByTran",produces="application/json;charset=UTF-8",method=RequestMethod.GET) 
	@ResponseBody
	public String findScannPayByTran(HttpServletRequest request, HttpServletResponse response) {
 		String outTradeNo = request.getParameter("outTradeNo");
 		String transactionID=request.getParameter("transactionID");
 		System.out.println("********************************outTradeNo:"+outTradeNo);
		String result = "";
		ScanPayQueryReqData scanPayQueryReqData = new ScanPayQueryReqData(transactionID, outTradeNo);
		Map<String, String> resultMap = new HashMap<String, String>();
		try {
			result = WXPay.requestScanPayQueryService(scanPayQueryReqData);
			System.out.println("********************************result:"+result);
			resultMap = XMLUtils.getResult(result);
			result=JSONObject.fromObject(resultMap).toString();
			String result_code=resultMap.get("result_code");
			System.out.println("***************************************result_code:"+result_code);
			String trade_state=resultMap.get("trade_state");
			System.out.println("***************************************trade_state:"+trade_state);
			String transactionId=resultMap.get("transaction_id");
			System.out.println("***************************************transactionId:"+transactionId);
	      TycoinAccountRecharge tycoinAccountRecharge=tycoinAccountRechargeService.findOneBypaymentId(outTradeNo);
 			if("SUCCESS".equals(result_code)&&"SUCCESS".equals(trade_state)&&!"1".equals(tycoinAccountRecharge.getPaymentStatus())){
 				tycoinAccountRecharge.setShopTradeNo(transactionId);
				tycoinAccountRecharge.setPaymentStatus(1);
	        	tycoinAccountRechargeService.save(tycoinAccountRecharge);
 		   		tycoinAccountRechargeCallbackProcessService.rechargeCallbackProcess(tycoinAccountRecharge); 
	        	System.out.println("***************************************进来了！");
  			}
 			System.out.println("***************************************没进来！");
		} catch (Exception e) {
		}

		return result;

	}
	/**
	 * return 返回二维码的链接，二维码图片流
	 * **/
	
	@RequestMapping(value = "/tradePrecreate",produces="application/json;charset=UTF-8",method=RequestMethod.GET)
	@ResponseBody
	public String testTradePrecreate(HttpServletRequest request, HttpServletResponse response) {
    String result="";
     		   
   		   
   		String Charge= request.getParameter("Charge");
		String GoodsName= request.getParameter("GoodsName");
 		String UserId= request.getParameter("UserId");
		String AddIp=  IpRequestUtils.getRemoteHost(request);
		long current= System.currentTimeMillis();
		
		TycoinAccountRecharge tycoinAccountRecharge=new TycoinAccountRecharge();
		String outTradeNo = "WxTran" +current+ (long) (Math.random() * 1000000000000L);
		    SimpleDateFormat formatter3 = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");  
		    String order_create_time3=formatter3.format(current); 
		    
		  tycoinAccountRecharge.setLogno(RandomUtils.getRandomString(16));
			tycoinAccountRecharge.setPaymentId(outTradeNo);
			tycoinAccountRecharge.setDateTime(current);
			tycoinAccountRecharge.setFee("0");
			tycoinAccountRecharge.setIsOnline("0");
			tycoinAccountRecharge.setMoney(Charge);
				tycoinAccountRecharge.setMoneyfloat(((float)Integer.valueOf(Charge))/100);
 			tycoinAccountRecharge.setUserId(UserId);
			tycoinAccountRecharge.setAddip(AddIp);
			tycoinAccountRecharge.setPaymentStatus(0);
			tycoinAccountRecharge.setPaymentTime(order_create_time3);

			tycoinAccountRecharge.setPayMode(1);
		     tycoinAccountRechargeService.save(tycoinAccountRecharge);
        
    WepayService wepayService=new WepayService();
    String url=wepayService.qrPay(outTradeNo,GoodsName, AddIp, Integer.valueOf(Charge));
	result = "{\"result_code\":\"0000\",\"return_msg\":\"\",\"imgpayUrl\":\""+url+"\",\"transaction_id\":\"" +outTradeNo + "\"}";
    return result;
	}
	
	

 
 	
	

	@RequestMapping(value = "/RollbackcannPayByTran",produces="application/json;charset=UTF-8",method=RequestMethod.GET)
	@ResponseBody
	public String backcannPayByTran(HttpServletRequest request, HttpServletResponse response) {
		String transactionID = request.getParameter("transactionID");
		String totalFee=request.getParameter("totalFee");
 		String result = "";
		Map<String, String> resultMap = new HashMap<String, String>();
 		RefundReqData reverseReqData=new RefundReqData("",transactionID,transactionID+"0000",Integer.valueOf(totalFee),Integer.valueOf(totalFee));
  		try {
 		 	   result=WXPay.requestRefundService(reverseReqData);
 				resultMap = XMLUtils.getResult(result);
				result = JSONObject.fromObject(resultMap).toString();
				String result_code = resultMap.get("result_code");
				String return_code = resultMap.get("return_code");
					TycoinAccountRecharge tycoinAccountRecharge=tycoinAccountRechargeService.findOneBypaymentId(transactionID);
				if ("SUCCESS".equals(result_code) && "SUCCESS".equals(return_code)) {
			 		   boolean boo=	  tycoinAccountRechargeCallbackProcessService.tycoinAccountRechargeCallBackSaveOrUpdate(tycoinAccountRecharge, request, response);
				}
   		         System.out.println(result);
		} catch (Exception e) {
		}

		return result;

	}
	
	
	  
  
 
	
	
	@RequestMapping(value = "/notiy_return",method=RequestMethod.POST)
 	public String notiy_return(HttpServletRequest request,HttpServletResponse response) throws IOException {
 		 System.out.println("------------我已经进入微信了异步回调----------");
 		
		System.out.println("----接收微信发来的消息---");
		BufferedReader reader = request.getReader();
        String line = "";
       StringBuffer inputString = new StringBuffer();
       try{
        while ((line = reader.readLine()) != null) {
            inputString.append(line);
            }
            request.getReader().close();
            System.out.println("----接收到的报文---"+inputString.toString());
            
            Map maps = GetWxOrderno.doXMLParse(inputString.toString());
    	    
           // Map<Object, Object> map = XMLUtil.doXMLParse(inputString.toString());
        for(Object keyValue : maps.keySet()){
            System.out.println(keyValue+"="+maps.get(keyValue));
        }
        System.out.println("===============result_code:"+maps.get("result_code"));
        String out_trade_no=maps.get("out_trade_no").toString();
        String total_fee=maps.get("total_fee").toString();
        String trade_no=maps.get("transaction_id").toString();
        /*String uid=request.getParameter("uid"); 
        String type=request.getParameter("type");               
        System.out.println("uid>>>>>>>>>>:"+uid);
        System.out.println("type>>>>>>>>>>:"+type);*/
        //String uid = new String(request.getParameter("uid").getBytes("ISO-8859-1"),"UTF-8");
    	System.out.println("----TRADE_FINISHED:"+out_trade_no);
        if (maps.get("result_code").toString().equalsIgnoreCase("SUCCESS")) {
         	TycoinAccountRecharge  tycoinAccountRecharge=tycoinAccountRechargeService.findOneBypaymentId(out_trade_no);
         	if(tycoinAccountRecharge!=null&&tycoinAccountRecharge.getPaymentStatus()!=1){
            	tycoinAccountRecharge.setPaymentStatus(1);
            	tycoinAccountRecharge.setShopTradeNo(trade_no);
            	tycoinAccountRecharge.setReturnText(JSONObject.fromObject(maps).toString());
            	tycoinAccountRechargeService.save(tycoinAccountRecharge);
    			tycoinAccountRechargeCallbackProcessService.rechargeCallbackProcess(tycoinAccountRecharge);  
         	}

         } 
        } catch(Exception e){
           e.getStackTrace();
         }
       return "success";
 		 
  	}
	
	public String  isNotparam(Map<String,String> map){
		String result="";
 		for (Map.Entry<String, String> entry : map.entrySet()) {  
  		     if(!org.apache.commons.lang3.StringUtils.isNotBlank(entry.getValue())){
	             result="{result_code:\"1001\",return_msg:\""+entry.getKey()+"参数不能为空\"}";
	        }
		}  
 		return result;
		
	}
	
	
	
	private String  setOpenId(HttpServletRequest request) {
		String code=request.getParameter("code");
		  request.getSession().setAttribute("code", code);
		  String oauth_url = Constants.oauth_url.replace("APPID", Constants.appid).replace("SECRET", Constants.appsecret).replace("CODE", String.valueOf( request.getSession().getAttribute("code")));
		  log.info("oauth_url:"+oauth_url);
		  JSONObject jsonObject = CommonUtil.httpsRequest(oauth_url, "POST", null);
		  log.info("jsonObject:"+jsonObject);
		  Object errorCode = jsonObject.get("errcode");
		  if(errorCode != null) {
		  log.info("code不合法");
		  }else{
		  String openId = jsonObject.getString("openid");
		  log.info("openId:"+openId);
		  request.getSession().setAttribute("openId", openId);
		  return openId;
		  }
		  return "";
		 }
		/**oauth_url返回的格式是：
		　　{ 
		　　　"access_token":"ACCESS_TOKEN", 
		　　　"expires_in":, 
		 "refresh_token":"REFRESH_TOKEN", 
		 "openid":"OPENID", "scope":"SCOPE", 
		 "unionid": "o_bmasdasdsad_sgVthMZOPfL"
		 }
		Code无效时：
		　　{
		　　 "errcode":
		　　　,"errmsg":"invalid code"
		 }**/



}
